<template>
  <el-dialog
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    destroy-on-close
    title="告警模型"
    :visible.sync="dialogVisible"
    width="1300px"
    custom-class="crud-dialog"
    :before-close="handleClose"
    append-to-body
    center
  >
    <div class="set-module">
      <el-form ref="conform" :model="form" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="告警模型：" prop="modelCode" :rules="[{ required: true, message: '请选择告警模型', trigger: 'change' }]">
              <el-select v-model="form.modelCode" filterable clearable @change="handleModelChange">
                <el-option
                  v-for="(witem, windex) in modelArr"
                  :key="windex"
                  :label="witem.label"
                  :disabled="witem.disabled"
                  :value="witem.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item
              label="处理时效："
              type="number"
              :rules="[
                { required: true, message: '请输入时效', trigger: 'blur' },
                { pattern: /^\d+$/, message: '请输入数字', trigger: 'blur' }
              ]"
              :prop="`processingAgeing`"
            >
              <el-input v-model="form.processingAgeing" maxlength="3">
                <template slot="append">分钟</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="持续时间："
              type="number"
              :rules="[
                { required: true, message: '请输入持续时间', trigger: 'blur' },
                { pattern: /^\d+$/, message: '请输入数字', trigger: 'blur' }
              ]"
              :prop="`configJson.continuousTime`"
            >
              <el-input v-model="form.configJson.continuousTime" maxlength="3">
                <template slot="append">分钟</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              v-if="form.modelCode == 'QYXS'"
              label="最低速度："
              type="number"
              :rules="[
                { required: true, message: '请输入最低速度', trigger: 'blur' },
                { pattern: /^\d+$/, message: '请输入数字', trigger: 'blur' }
              ]"
              :prop="`configJson.minSpeed`"
            >
              <el-input v-model="form.configJson.minSpeed" maxlength="3">
                <template slot="append">节</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              v-if="form.modelCode == 'QYXS'"
              label="最高速度："
              type="number"
              :rules="[
                { required: true, message: '请输入最高速度', trigger: 'blur' },
                { pattern: /^\d+$/, message: '请输入数字', trigger: 'blur' }
              ]"
              :prop="`configJson.maxSpeed`"
            >
              <el-input v-model="form.configJson.maxSpeed" maxlength="3">
                <template slot="append">节</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              v-if="form.modelCode == 'WANGDMB'"
              label="船舶类别："
              :prop="`configJson.shipTypes`"
              :rules="[{ required: true, message: '请选择船舶类别', trigger: 'change' }]"
            >
              <el-select v-model="form.configJson.shipTypes" multiple filterable clearable>
                <el-option v-for="(item, index) in shipTypeArr" :key="item.value" :label="item.lable" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item v-if="form.modelCode == 'QYXH'" label="禁入时间：">
              <el-form-item
                label-width="55px"
                style="width: 600px; margin-bottom: 20px"
                v-for="(domain, nindex) in form.configJson.timeAreas"
                :prop="`configJson.timeAreas.${nindex}.timeAreasArr`"
                :rules="{ required: true, message: '选择时间', trigger: 'blur' }"
                :key="nindex"
                label="时间"
              >
                <el-time-picker
                  v-model="domain.timeAreasArr"
                  is-range
                  range-separator="至"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  placeholder="选择时间"
                  format="HH:mm"
                  style="width: 75%"
                >
                </el-time-picker>
                <el-button type="danger" style="margin-left: 10px" @click.prevent="removeDomain(nindex)" size="small" v-if="nindex != 0"
                  >删除</el-button
                >
                <el-button size="small" type="primary" style="margin-left: 10px" @click="addDomain()" v-if="nindex == 0">新增</el-button>
              </el-form-item>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="handleOk">确 定</el-button>
      <el-button @click="handleClose">取 消</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { addWarnModel, getWarnModelDetail, editWarnModel } from '@/api/channelArea'

import { filterTime } from '@/utils/util'
export default {
  props: {
    areaInfo: {
      type: Object,
      default: () => {
        return {}
      }
    },
    shipTypeArr: {
      type: Array,
      default: () => {
        return []
      }
    },
    modelArr: {
      type: Array,
      default: () => {
        return []
      }
    }
  },

  data() {
    return {
      dialogVisible: false,
      loading: false,
      form: {
        configJson: {}
      }
    }
  },
  mounted() {},
  methods: {
    async show(row) {
      this.dialogVisible = true
      if (!row) {
        this.form.areaId = this.areaInfo.id
        // this.form.configJson = {
        //   timeAreas: [{ timeAreasArr: [new Date(2016, 9, 0, 0, 0), new Date('Jun 2,2017 23:59:59')] }]
        // }
      } else {
        const { result } = await getWarnModelDetail(row.id)
        const formData = {
          id: result.id,
          areaId: result.areaId,
          modelCode: result.modelCode,
          processingAgeing: result.processingAgeing
        }

        formData.configJson = JSON.parse(result.configJson)
        formData.configJson &&
          formData.configJson.timeAreas &&
          formData.configJson.timeAreas.length > 0 &&
          formData.configJson.timeAreas.forEach((v) => {
            v.timeAreasArr = [`2016-11-11 ${v.timeAreasArr[0]}`, `2016-11-11 ${v.timeAreasArr[1]}`]
          })
        this.form = formData
      }
    },

    addDomain() {
      this.form.configJson.timeAreas.push({
        timeAreasArr: [new Date(2016, 9, 0, 0, 0), new Date('Jun 2,2017 23:59:59')]
      })
    },
    removeDomain(index) {
      this.form.configJson.timeAreas.splice(index, 1)
    },

    handleOk() {
      this.$refs['conform'].validate(async (valid) => {
        if (valid) {
          this.loading = true

          // 深复制对象，解决form表单，configJson对象中时间输入框假死问题
          const formData = JSON.parse(JSON.stringify(this.form))

          if (formData.configJson.timeAreas && formData.configJson.timeAreas.length > 0) {
            formData.configJson.timeAreas.forEach((val) => {
              val.timeAreasArr = [filterTime(val.timeAreasArr[0]), filterTime(val.timeAreasArr[1])]
            })
          }

          formData.areaId = this.areaInfo.id

          if (formData.configJson && formData.configJson.continuousTime) {
            formData.configJson.continuousTime = Number(formData.configJson.continuousTime)
          }
          if (formData.configJson && formData.configJson.minSpeed) {
            formData.configJson.minSpeed = Number(formData.configJson.minSpeed)
          }
          if (formData.configJson && formData.configJson.maxSpeed) {
            formData.configJson.maxSpeed = Number(formData.configJson.maxSpeed)
          }
          if (formData.configJson && formData.configJson.minSpeed != undefined && formData.configJson.maxSpeed != undefined) {
            if (formData.configJson.minSpeed >= formData.configJson.maxSpeed) {
              this.$message.warning(`最高速度不能小于等于最低速`)
              return
            }
          }
          formData.configJson = JSON.stringify(formData.configJson)

          if (formData.id) {
            await editWarnModel(formData)
            this.$message.success(`更新告警模型成功`)
          } else {
            await addWarnModel(formData)
            this.$message.success(`添加告警模型成功`)
          }

          this.loading = false

          this.handleClose()
          this.$emit('handleRefresh')
        } else {
          return false
        }
      })
    },

    handleClose() {
      this.dialogVisible = false
      this.form = {
        configJson: {}
      }
    },
    handleModelChange(value) {
      const configJson = {}

      // 闯入限航区域区，至少输入一条禁入时间范围
      if (value == 'QYXH') {
        configJson.timeAreas = [{ timeAreasArr: [new Date(2016, 9, 0, 0, 0), new Date('Jun 2,2017 23:59:59')] }]
      }
      this.form.configJson = configJson
    }
  }
}
</script>
<style>
input[type='number']::-webkit-inner-spin-button,
input[type='number']::-webkit-outer-spin-button {
  -webkit-appearance: none;
  margin: 0;
}
</style>
<style scoped lang="scss">
@import '@/assets/styles/variables';
::v-deep .el-dialog__body {
  max-height: 700px !important;
  overflow-y: scroll;
  @include scrollBar();
}
.set-module {
  // max-height: 900px;
  // overflow-y: scroll;
  // @include scrollBar();

  ::v-deep .el-select {
    width: 100% !important;
  }
  .select-style1 {
    ::v-deep .el-select {
      width: 42% !important;
    }
  }
}
</style>
